package tgc.edu.yzy.custom;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;

import tgc.edu.yzy.entity.Book;
import tgc.edu.yzy.entity.Record;
import tgc.edu.yzy.entity.User;
import tgc.edu.yzy.security.User2;
import tgc.edu.yzy.service.BookService;
import tgc.edu.yzy.service.RecordService;
@Controller
public class Custom {
	@Autowired
	private BookService bookservice;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private RecordService recordservice;
	private String path="c:/image";
	/***
	 * 储存file到文件加中
	 * @param file 传过来的对象
	 * @return uuid 返回储存的UUID
	 */
	public String file(MultipartFile file) {
		String uuid = UUID.randomUUID().toString();
		File files=new File(this.path);
		if(!files.isDirectory()) {
			files.mkdir();
		}
		File saveFile=new File(files,uuid);
		try {
			file.transferTo(saveFile);
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
			return uuid;
		}
		return uuid;
	}
	/***
	 * 下载文件
	 * @param id
	 * @param request
	 * @param response
	 */
	public void download(Integer id, HttpServletRequest request, HttpServletResponse response) {
		Book books = bookservice.findById(id);
		String filename = books.getFilename();
		filename = getStr(request, filename);//文件名处理 兼容多个版本
		String uuid= books.getUuid();
		File file = new File(this.path,uuid);
		if(file.exists()) {
			FileInputStream fis;
			try {
				fis = new FileInputStream(file);
				response.setContentType("application/x-msdownload");
				response.addHeader("Content-Disposition", "attachment; filename=" + filename );
				ServletOutputStream out = response.getOutputStream();
				byte[] buf=new byte[2048];
				int n=0;
				while((n=fis.read(buf))!=-1){
					out.write(buf, 0, n);
				}
				fis.close();
				out.flush();
				out.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private String getStr(HttpServletRequest request, String fileName) {
		String downloadFileName = null;
		//仅提供了部分代码，因为我们已经明确问题的所在，知道修改那一部分了，（代码中downloadFileName 即代表 *=utf-8'zh_cn'文件名.xx部分）
        String agent = request.getHeader("USER-AGENT");  
         try {
            	 if(agent != null && agent.toLowerCase().indexOf("firefox") > 0){
            		 //downloadFileName = "=?UTF-8?B?" + (new String(Base64Utils.encode(fileName.getBytes("UTF-8")))) + "?=";
            		 //设置字符集
            		 downloadFileName = "=?UTF-8?B?" + Base64Utils.encodeToString(fileName.getBytes("UTF-8")) + "?=";
            	 }else{
            		 downloadFileName =  java.net.URLEncoder.encode(fileName, "UTF-8");
            	 }
		} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
		}
        return downloadFileName;
	}
	/***
	 * 获取时间
	 * @return
	 */
	public  String time() {
		Date date=new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(date);
	}
	/***
	 * 登录 登出
	 */
	public void denglu(String uuid) {
		Record record=new Record();
		SecurityContext ctx = SecurityContextHolder.getContext();
	    Authentication auth = ctx.getAuthentication();
	    User2 user = (User2) auth.getPrincipal();
	    record.setName(user.getName());//存入姓名
	    String ip = request.getRemoteAddr();
	    record.setIp(ip);//存入IP
	    record.setTime(time()); 
	    if(uuid==null) {
	    	record.setContent("登录");
	    	record.setOperation("成功登录");
	    	
	    }else {
	    	record.setContent("登出");
	    	record.setOperation("安全退出");
	    }
	    recordservice.save(record);
	}
	public void booksrecord(User user, Book book,String content,String operation) {
		Record record=new Record();
		SecurityContext ctx = SecurityContextHolder.getContext();
	    Authentication auth = ctx.getAuthentication();
	    User2 userss = (User2) auth.getPrincipal();
	    record.setName(userss.getName());//存入姓名
	    String ip = request.getRemoteAddr();
	    record.setIp(ip);//存入IP
	    record.setTime(time());//存入操作时间
	    record.setBook(book);
	    record.setUser(user);
	    record.setOperation(operation);
	    record.setContent(content);
	    recordservice.save(record);
		
	}
	
	public Integer userid() {
		SecurityContext ctx = SecurityContextHolder.getContext();
	    Authentication auth = ctx.getAuthentication();
	    User2 userss = (User2) auth.getPrincipal();
	    return userss.getId();
	}
}
